extends Control

signal got_user

var users : Array
var current_index : int
var userdata := "user://userdata/"

func _ready():
	var dir := Directory.new()
	if not dir.dir_exists(userdata):
		dir.make_dir(userdata)
	reload_user_list()

func reload_user_list():
	users = dir_contents(userdata)
	var item_list : ItemList = $VBoxContainer/ScrollContainer/ItemList
	item_list.clear()
	for u in users:
		item_list.add_item(u)

func dir_contents(path):
	var arr := []
	var dir := Directory.new()
	if dir.open(path) == OK:
		dir.list_dir_begin()
		var file_name = dir.get_next()
		while file_name != "":
			if dir.current_is_dir() and file_name != "." and file_name != "..":
				arr.append(file_name)
			file_name = dir.get_next()
	return arr


func _on_NewPlayerButton_pressed():
	var name : String = $VBoxContainer/HBoxMenu/LineEdit.text
	print(users)
	if not users.has(name) and name.is_valid_filename():
		var dir := Directory.new()
		dir.make_dir(userdata + name)
		reload_user_list()



func _on_ItemList_item_selected(index):
	var item_list : ItemList = $VBoxContainer/ScrollContainer/ItemList
	$VBoxContainer/HBoxMenu/DeleteButton.disabled = false
	$VBoxContainer/SelectButton.disabled = false
	current_index = index


func _on_DeleteButton_pressed():
	remove_recursive(userdata + Globals.current_user)
	Globals.current_user = ""
	reload_user_list()

func remove_recursive(path):
	var directory = Directory.new()
	
	# Open directory
	var error = directory.open(path)
	if error == OK:
		# List directory content
		directory.list_dir_begin(true)
		var file_name = directory.get_next()
		while file_name != "":
			if directory.current_is_dir():
				remove_recursive(path + "/" + file_name)
			else:
				directory.remove(file_name)
			file_name = directory.get_next()
		
		# Remove current path
		directory.remove(path)
	else:
		print("Error removing " + path)


func _on_SelectButton_pressed():
	var item_list : ItemList = $VBoxContainer/ScrollContainer/ItemList
	var index = item_list.get_selected_items()[0]
	var name = item_list.get_item_text(index)
	if name != "":
		Globals.current_user = name
		emit_signal("got_user", name)
